<!--
*@Author: zt
*@Description: 请假管理
*@Date: 2024-08-14
-->
<template>
  <a-layout class="f-h-100">
    <u-table-header class="s-bg-white">
      <a-form
        :model="searchF"
        :inline="true"
        class="f-search-tool-200"
        style="--width: 220px"
        label-width="80px"
        layout="horizontal"
      >
        <a-row>
          <a-col :span="10">
            <a-form-item label="考勤类型">
              <u-cascader
                v-model:value="searchF.model.applicanttype"
                :options="applicanttypeType"
                :fieldNames="{ label: 'name', value: 'id' }"
              />
            </a-form-item>
            <a-form-item label="审核状态">
              <u-cascader
                v-model:value="searchF.model.status"
                :options="APP_STATUS"
                :fieldNames="{ label: 'name', value: 'code' }"
              />
            </a-form-item>
            <u-icon-button itype="search" @click="getSearch()">
              查询
            </u-icon-button>
          </a-col>
          <a-col :span="14">
            <a-row>
              <a-col flex="1">
                <a-row justify="end">
                  <a-space>
                    <u-icon-button itype="record" @click="showFlow = true">
                      流程记录
                    </u-icon-button>
                    <u-icon-button itype="report" @click="auditAbout('1')">
                      上报
                    </u-icon-button>
                    <u-icon-button itype="delete" @click="deleteBtn()">
                      删除
                    </u-icon-button>
                  </a-space>
                </a-row>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </a-form>
    </u-table-header>
    <u-table-content>
      <u-table
        :columns="columns"
        :data="tabData"
        v-loading="tabLoading"
        v-model:pagination="pagenation"
        :scroll="{ y: useTableScroll() }"
        @onSelect="({ selectedRows }) => (tabSelData = selectedRows)"
        @onDblclick="onDblclick"
        @change="getSearch()"
      />
    </u-table-content>
  </a-layout>

  <!-- 考勤编辑 -->
  <VacatEdit
    v-model:open="showEdit"
    :busiType="busiType"
    :keyid="keyid"
    :formDisabled="formDisabled"
    @success="getSearch(), (showEdit = false)"
    wrap-class-name="full-modal"
  />

  <!-- 流程记录 -->
  <u-act-flowd
    v-model:open="showFlow"
    :selDatas="tabSelData"
    busiType="leave_apply"
  />
</template>
<script lang="ts" setup>
import { formtTableEcho, formtTableEnum } from '@/util/format.ts'
import { isValue, nullC, numberC } from '@/util/common';
import { computed, h, onMounted, reactive, ref, watch } from 'vue';
import { useLoginStore, useBaseStore } from '@/store';
import { storeToRefs } from 'pinia';
import * as myCheckInApi from '@/service/personnel/myCheckIn/index';
import { alertC } from '@/util/common';
import { useTableScroll } from '@/hooks/useTable';
import {
  useReport,
  useSendWork,
  useReturnWork,
  IAuditParams,
} from '@/hooks/useAudit';
import VacatEdit from '../myCheckIn/VacatEdit.vue';
import dayjs from 'dayjs';
const { userInfo } = storeToRefs(useLoginStore());
const { APP_STATUS } = storeToRefs(useBaseStore());
// 打开编辑
let showEdit = ref<boolean>(false);
let busiType = ref<string>('');
let keyid = ref('');
let formDisabled = ref(false);

const showFlow = ref(false);
let searchF = reactive({
  current: 1,
  size: 100,
  sort: 'fkdeptid',
  order: 'ascending',
  model: {
    keywords: '',
    status: [1],
    // status: APP_STATUS.value,
    applicanttype: '',
    pageStatus: 1,
  },
});
const applicanttypeType = ref([
  {
    name: '加班',
    id: 1,
  },
  {
    name: '请假',
    id: 2,
  },
  {
    name: '离驻地',
    id: 3,
  },
]);

let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: total => `共 ${total} 条`,
});

const tabLoading = ref(false);
const total = ref(0);
const tabData = ref([]);
const tabSelData = ref([]);
let columns = ref([
  {
    dataIndex: 'index',
    title: '序号',
    width: 60,
    align: 'center',
    customRender: ({ text, record, index }) => {
      return index + 1;
    },
  },
  {
    title: '部门',
    width: 140,
    align: 'center',
    dataIndex: 'fkdeptname',
    sortable: 'custom',
  },
  {
    title: '申请人',
    width: 120,
    align: 'center',
    dataIndex: 'fkapplicant',
    sortable: 'custom',
  },
  {
    title: '类型',
    width: 120,
    align: 'center',
    dataIndex: 'applicanttype_echo',
    sortable: 'custom',
  },
  {
    title: '填报时间',
    width: 120,
    align: 'center',
    dataIndex: 'createtime',
    sortable: 'custom',
    customRender: ({ text }) => {
      return (text || '').split(' ')[0];
    },
  },
  {
    title: '开始时间',
    width: 120,
    align: 'center',
    dataIndex: 'startdate',
    sortable: 'custom',
    customRender: ({ text, record }) => {
      if (record.applicanttype_echo == '加班') {
        return dayjs(text).format('YYYY-MM-DD HH:mm');
      } else {
        return (text || '').split(' ')[0];
      }
    },
  },
  {
    title: '结束时间',
    width: 120,
    align: 'center',
    dataIndex: 'endstart',
    sortable: 'custom',
    customRender: ({ text, record }) => {
      if (record.applicanttype_echo == '加班') {
        return dayjs(text).format('YYYY-MM-DD HH:mm');
      } else {
        return (text || '').split(' ')[0];
      }
    },
  },
  {
    title: '事由',
    width: 100,
    align: 'center',
    dataIndex: 'reason',
    // fixed: "right",
  },
  {
    title: '审核状态',
    width: 100,
    align: 'center',
    dataIndex: 'status_echo',
    // fixed: "right",
  },
]);

onMounted(async () => {
  getSearch();
});

// 获取列表数据
const getSearch = async (current?: number) => {
  if (searchF.model.applicanttype instanceof Array) {
    searchF.model.applicanttype = searchF.model.applicanttype[0];
  }
  if (searchF.model.status instanceof Array) {
    searchF.model.status = searchF.model.status[0];
  }
  if (current == 1) {
    pagenation.current = 1;
  }
  let tform = JSON.parse(JSON.stringify(searchF));

  tform.current = pagenation.current;
  tform.size = pagenation.pageSize;
  tabLoading.value = true;
  const res = await myCheckInApi.page({ ...tform });
  if (res.code == 0) {
    let data = formtTableEcho(res.data.records);
    data.map(e => {
      e.applicanttype == 1
        ? (e.applicanttype_echo = '加班')
        : e.applicanttype == 2
        ? (e.applicanttype_echo = '请假')
        : e.applicanttype == 3
        ? (e.applicanttype_echo = '离驻地')
        : '备勤';
      if (e.status == 1) {
        e.status_echo = '未提交';
      } else if (e.status == 2) {
        e.status_echo = '审核中';
      } else if (e.status == 3) {
        e.status_echo = '审核完成';
      } else if (e.status == 4) {
        e.status_echo = '已退回';
      }
    });
    tabData.value.splice(0, tabData.value.length, ...data);
    pagenation.total = numberC(res.data.total);

    tabLoading.value = false;
  }
};

// 删除功能
const deleteBtn = (record?: any) => {
  if (tabSelData.value.length == 0) {
    alertC('请先选择要删除的数据！');
    return;
  }

  let ids = tabSelData.value.map(item => item.keyid);
  if (record) {
    ids = [record.keyid];
  }
  tabLoading.value = true;
  myCheckInApi
    .del({ ids: ids.join(',') })
    .then(res => {
      tabLoading.value = false;
      if (res.code == 0) {
        getSearch();
        alertC(res.msg, 'success');
      } else {
        alertC(res.msg, 'warning');
      }
    })
    .catch(err => {
      tabLoading.value = false;
    });
};

// 上报、审核、退回
const auditAbout = async (type: string | number) => {
  tabLoading.value = true;
  const auditParams: IAuditParams = {
    type: 'leave_apply',
    selDatas: tabSelData.value,
  };
  try {
    // 上报
    if (type == 1) {
      const res = await useReport(auditParams);
    }
    // 审核
    else if (type == 2) {
      const res = await useSendWork(auditParams);
    }
    // 退回
    else if (type == 3) {
      const res = await useReturnWork(auditParams);
    }
    pagenation.current = 1;
    getSearch();
  } catch (error) {}
  tabLoading.value = false;
};

//填报列表数据展示

const onDblclick = record => {
  keyid.value = record['keyid'];
  busiType.value = record['applicanttype'];
  if (record['status'] == 3 || record['status'] == 2) {
    formDisabled.value = true;
  } else {
    formDisabled.value = false;
  }
  showEdit.value = true;
};
</script>
<style lang="scss">
.u-jhk-serch-datepicker {
  .el-range-separator {
    padding: 0;
    width: unset;
  }
}
</style>
